﻿/* Copyright (C) 2007-2010 STS Soft

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

using System.IO;
using System.Xml.Linq;
using STSdb.General.Collections;

namespace STSdb.Persist
{
    public class XElementIndexerPersist : IIndexerPersist<XElement>
    {
        public readonly DeflateIndexerPersist<string> deflate = new DeflateIndexerPersist<string>(new PrimitiveStringIndexerPersist());
        
        #region IIndexerPersist<XElement> Members

        public void Store(BinaryWriter writer, IIndexer<XElement> values)
        {
            deflate.Store(writer, new InternalIndexer(values));
        }

        public void Load(BinaryReader reader, IIndexer<XElement> values)
        {
            deflate.Load(reader, new InternalIndexer(values));
        }

        #endregion

        private class InternalIndexer : IIndexer<string>
        {
            private IIndexer<XElement> indexer;

            public InternalIndexer(IIndexer<XElement> indexer)
            {
                this.indexer = indexer;
            }
            
            #region IIndexer<string> Members

            public string this[int index]
            {
                get
                {
                    XElement element = indexer[index];
                    if (element == null)
                        return null;

                    return element.ToString();
                }
                set
                {
                    if (value != null)
                        indexer[index] = XElement.Parse(value);
                    else
                        indexer[index] = null;
                }
            }

            public int Count
            {
                get { return indexer.Count; }
            }

            #endregion
        }
    }
}
